package com.engine.cusupload.web;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2024-04-09
 * @Description: 文件上传接口
 * @ModifyLog:
 **/

public class WeaCusuploadWeb extends BaseBean {
    /**
     * @Description: 文件上传
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2024-04-09
     */
    @POST
    @Path("/upload")
    @Produces({MediaType.MULTIPART_FORM_DATA})
    public String upload(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        try {
            BaseBean baseBean = new BaseBean();
            String realPath = request.getRealPath("/");
            baseBean.writeLog(">>>>>uploadfile.jsp>>>>>realPath=" + realPath);
            String path = Util.null2String(request.getParameter("path"));
            baseBean.writeLog(">>>>>uploadfile.jsp>>>>>path=" + path);
            String status = "";
            String message = "";
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                    for (FileItem item : multiparts) {
                        baseBean.writeLog(">>>>>uploadfile.jsp>>>>>item=" + item);
                        if (!item.isFormField()) {

                            String name = new File(item.getName()).getName();
                            baseBean.writeLog(">>>>>uploadfile.jsp>>>>>name=" + name);
                            String fileSeparator = File.separator;
                            baseBean.writeLog(">>>>>uploadfile.jsp>>>>>fileSeparator=" + fileSeparator);
                            if (fileSeparator.equals("\\")) {
                                path = path.replace("/", "\\");
                            }
                            baseBean.writeLog(">>>>>uploadfile.jsp>>>>>path=" + path);
                            ensureDirectoryExists(realPath + path);
                            String filePath = realPath + path + name;
                            byte[] yourByteArray = item.getName().getBytes(StandardCharsets.UTF_8);
                            try {
                                byteArrayToFile(yourByteArray, filePath);
                                baseBean.writeLog("Byte array successfully written to file: " + filePath);
                            } catch (IOException e) {
                                baseBean.writeLog("Error writing byte array to file: " + e.getMessage());
                                e.printStackTrace();
                            }
                            baseBean.writeLog(">>>>>uploadfile.jsp>>>>>filePath=" + filePath);


                        }
                    }
                } catch (Exception e) {
                    status = "except";
                    message = "Error writing input stream to file: " + e.getMessage();
                    e.printStackTrace();
                }
            } else {
                status = "error";
                message = "Request is not multipart content";
            }
            apidatas.put( "api_status", status );
            apidatas.put( "api_msg", message );
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put( "api_status", false );
            apidatas.put( "error_message", "请求接口异常" );
        }
        return JSONObject.toJSONString( apidatas );
    }

    public static void ensureDirectoryExists(String directoryPath) {
        File directory = new File(directoryPath);

        // 判断目录是否存在
        if (!directory.exists()) {
            // 目录不存在，尝试创建
            if (!directory.mkdirs()) {
                throw new RuntimeException("Failed to create directory: " + directoryPath);
            }
        } else if (!directory.isDirectory()) {
            throw new IllegalArgumentException("Specified path is not a directory: " + directoryPath);
        }

        // 确保目录可写，以防后续操作因权限问题失败
        if (!Files.isWritable(directory.toPath())) {
            throw new IllegalStateException("Directory is not writable: " + directoryPath);
        }
    }


    public static void byteArrayToFile(byte[] byteArray, String filePath) throws IOException {
        // Step 1: Create a File object representing the desired file path
        File file = new File(filePath);

        // Step 2: Create a FileOutputStream to write to the file
        try (FileOutputStream fos = new FileOutputStream(file)) {
            // Step 3: Write the byte array to the file using the OutputStream
            fos.write(byteArray);
        }
    }

}
